package com.aruba.bulethoothdemoapplication.viewmodel;

import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.OnLifecycleEvent;

import com.aruba.bulethoothdemoapplication.model.BleDevice;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by aruba on 2022/4/25.
 */
public class SelectDeviceViewModel extends AndroidViewModel implements LifecycleObserver {
    private static final long SCAN_PERIOD = 15 * 1000;

    private MutableLiveData<List<BleDevice>> listMutableLiveData = new MutableLiveData<>(new ArrayList<>());
    public LiveData<List<BleDevice>> datas = listMutableLiveData;
    private BluetoothAdapter mBluetoothAdapter;
    final BroadcastReceiver bReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                handleFoundDevice(device);
            }
        }
    };
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable runnable;
    private MutableLiveData<BleDevice> selectBleDevice = new MutableLiveData<>();

    public SelectDeviceViewModel(@NonNull Application application) {
        super(application);
        init();
    }

    private void init() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            toast("该设备蓝牙功能不可用");
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void onResume() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        getApplication().registerReceiver(bReceiver, intentFilter);
        scanDevice();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void onPause() {
        if (runnable != null)
            handler.removeCallbacks(runnable);

        getApplication().unregisterReceiver(bReceiver);
        listMutableLiveData.setValue(new ArrayList<>());
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy() {
        mBluetoothAdapter.cancelDiscovery();
    }

    public void scanDevice() {
        if (!mBluetoothAdapter.isDiscovering()) {
            ArrayList<BleDevice> devices = new ArrayList<>();

            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    BleDevice bleDevice = new BleDevice(device.getName(), device.getAddress());
                    devices.add(bleDevice);
                }
            }

            listMutableLiveData.setValue(devices);

            mBluetoothAdapter.startDiscovery();

            //后面改coroutine 
            if (runnable == null)
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        mBluetoothAdapter.cancelDiscovery();
                    }
                };
            handler.postDelayed(runnable, SCAN_PERIOD);
        }
    }

    private void handleFoundDevice(BluetoothDevice device) {
        BleDevice bleDevice = new BleDevice(device.getName(), device.getAddress());
        bleDevice.setName(TextUtils.isEmpty(bleDevice.getName()) ? "未知设备" : bleDevice.getName());
        boolean deviceFound = false;
        List<BleDevice> bluetoothDevices = listMutableLiveData.getValue();
        if (bluetoothDevices != null) {
            for (BleDevice item : bluetoothDevices) {
                if (item.getAddress().equals(bleDevice.getAddress())) {
                    deviceFound = true;
                    break;
                }
            }
        }
        if (!deviceFound) {
            bluetoothDevices.add(bleDevice);
            listMutableLiveData.setValue(bluetoothDevices);
        }
    }

    public void setSelectBleDevice(BleDevice selectBleDevice) {
        this.selectBleDevice.setValue(selectBleDevice);
    }

    public MutableLiveData<BleDevice> getSelectBleDevice() {
        return selectBleDevice;
    }

    public final boolean isBluetoothEnabled() {
        return mBluetoothAdapter.enable();
    }


    private void toast(String text) {
        Toast.makeText(getApplication(), text, Toast.LENGTH_SHORT).show();
    }

}
